<template>
  <!-- 总容器 -->
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <div class="icon-location-box">
        <div class="icon-location"></div>
      </div>
      <div class="location-text">
        沈阳市规划大厦
        <i class="fa fa-caret-down"></i>
      </div>
    </header>

    <!-- search部分 -->
    <!-- 
			    搜索框部分（此块与search-fixed-top块宽度高度一致，用于当
				search-fixed-top块固定后，挡住下面块不要窜上去） 
    -->
    <div class="search">
      <!-- 当滚动条超过上面的定位块时，search-fixed-top块变成固定在顶部。 -->
      <div class="search-fixed-top" ref="fixedBox">
        <input class="search-box" placeholder="搜索饿了么商品名称" type="text">
        <i class="fa fa-search" @click="toSearch()"></i>
      </div>
    </div>

    <!-- 点餐分类部分 -->
    <ul class="foodtype">
      <li v-for="item in listBusinessType" :key="item.typeid" @click="toBusinessList(item.typeid)">
        <!-- 属性绑定指令  v-bind  简写方式-: -->
        <!-- <img v-bind:src = "item.typeimg" /> -->
        <img :src="item.typeimg" />
        <p>{{ item.typename }}</p>
      </li>
    </ul>

    <!-- 横幅广告部分 -->
    <div class="banner">
      <h3>品质套餐</h3>
      <p>搭配齐全吃得好</p>
      <a>立即抢购 &gt;</a>
    </div>

    <!-- 超级会员部分 -->
    <div class="supermember">
      <div class="left">
        <img src="../assets/super_member.png" />
        <h3>超级会员</h3>
        <p>&#8226; 每月享超值权益</p>
      </div>
      <div class="right" type="primary" @click="beVIP">{{ beVipButton }}&gt;</div>
    </div>

    <!-- 推荐商家部分 -->
    <div class="recommend">
      <div class="recommend-line"></div>
      <p>推荐商家</p>
      <div class="recommend-line"></div>
    </div>

    <!-- 推荐方式部分 -->
    <ul class="recommendtype">
      <li @click="comprehensive()">
        综合排序
        <i v-if="this.choose == 0" class="fa fa-caret-down"></i>
      </li>
      <li @click="nearestDistance()">
        距离最近
        <i v-if="this.choose == 1" class="fa fa-caret-down"></i>
      </li>
      <li @click="highestSales()">
        销量最高
        <i v-if="this.choose == 2" class="fa fa-caret-down"></i>
      </li>
      <li @click="showBusinessType()">
        筛选
        <i class="fa fa-filter" :class="{ rotateFilter: showCategories }"
          @click.stop="showCategories = !showCategories"></i>
        <div v-if="showCategories" class="category-box">
          <ul>
            <li v-for="item in listBusinessType" :key="item.typeid">
              <p @click="categorizeBusiness(item.typeid)">{{ item.typename }}</p>
            </li>
          </ul>
        </div>
      </li>
    </ul>

    <!-- 推荐商家列表部分 -->
    <ul class="business">
      <li v-for="item in listBusiness" :key="item.businessId" @click="toBusiness(item.businessId)">
        <div class="business-img">
          <div v-if="getBusinessQuantity(item.businessId) > 0" class="business-img-quantity">{{
            businessQuantities[item.businessId] }}</div>
          <img :src="item.businessImg" />
        </div>
        <div class="business-info">
          <div class="business-info-h">
            <h3>{{ item.businessName }}</h3>
            <div class="business-info-like">&#8226;</div>
            <!-- 小点 -->
          </div>
          <div class="business-info-star">
            <div class="business-info-star-left">
              <span v-for="n in countStar(item.remarks)" :key="n">
                <i class="fa fa-star"></i>
              </span>
              <p>{{ item.remarks }} 月售{{ item.sales }}单</p>
            </div>
            <div v-if="item.delivery > 0" class="business-info-star-right">蜂鸟专送</div>
          </div>
          <div class="business-info-delivery">
            <p>&#165;{{ item.starPrice }}起送 | &#165;{{ item.deliveryPrice }}配送</p>
            <p>{{ item.distance }}km | {{ item.deliveryTime }}分钟</p>
          </div>
          <div class="business-info-explain">
            <div>{{ item.businessExplain }}</div>
          </div>
          <div v-if="activeBusinessId === item.businessId" class="business-info-promotion-of-left">
            <div v-for="activity in item.activities" :key="activity.activityId" class="business-info-promotion-left">
              <!-- <div class="business-info-promotion-left-incon">{{ activity.activityType }}</div> -->
              <div class="business-info-promotion-left-incon"
                :class="`activity-type-${mapActivityTypeToClass(activity.activityType)}`">{{ activity.activityType }}
              </div>
              <p>{{ activity.activityContent }}</p>
            </div>
          </div>

          <div v-if="item.activity > 0" class="business-info-promotion-of-left">
            <div class="business-info-promotion-right" @click.stop="showPromotions(item.businessId)">
              <p>{{ item.activity }}个活动</p>
              <i class="fa fa-caret-left" :class="{ rotated: activeBusinessId === item.businessId }"></i>
            </div>
          </div>
        </div>
      </li>

    </ul>
  </div>
</template>

<script>
import { showConfirmDialog } from 'vant';
import {showDialog} from 'vant';

export default {
  data() {
    return {
      BusinessList: [],
      listBusinessType: [],
      listBusiness: [],
      listBusiness2: [],
      count: this.getBusinessListCount(),
      choose: 0,
      activeBusinessId: null, // 当前显示促销信息的商家 ID
      user: JSON.parse(sessionStorage.getItem("user")), //当前登录的用户
      businessQuantities: {}, // 存储每个 businessId 的数量
      showCategories: false,// 用来控制是否显示筛选框
      beVipButton: "立即开通"//初始化未开通的信息
    };
  },
  methods: {

    // 每当刷新界面，用户VIP状态发生改变，存储在sessionStorage内的VIP也要改变
    getUserInfo() {
      if(this.user==null)
      {
        console.log("----------------")
      }
      // console.log(username)
      // console.log(this.user)
      else{
        this.$http.get('/users/profile', {
        params: {
          username: this.user.username
        }
      })
        .then(res => {
          this.user = res.data.object
          sessionStorage.setItem("user", JSON.stringify(res.data.object));

          // 页面一挂载就开始查询是否为VIP
          if (this.user.vip == 1) {
            this.beVipButton = "权益中心"
          }
        })
      }
    },

    // // 成为会员
    // beVIP() {
    //   console.log(this.user.vip)
    //   if (this.user.vip == 1) {
    //     console.log("进入权益中心")
    //   }
    //   else if (window.confirm('您是否想要成为会员呢？') && this.user.vip == 0) {
    //     // console.log("用户点击是")
    //     // 用户点击了确认（是）按钮后的逻辑处理
    //     this.beVipButton = "权益中心"


    //     // console.log(this.user)
    //     //将users表内的状态更新为vip=1
    //     this.$http.post('/users/beVIP',
    //       {
    //         userId: this.user.userId
    //       })
    //   }
    // },

    // 成为会员
    beVIP() {

      if(this.user==null){

        this.$router.push('/login')
        return;
      }
      console.log(this.user.vip)
      if (this.user.vip == 1) {
        console.log("进入权益中心")
        this.$router.push('./vipcenter')
      }
      else {
        showConfirmDialog({
          title: '会员',
          message:
            '您是否想成为会员',
          theme: 'round-button',
        })
          .then(() => {
            // on confirm
            this.beVipButton = "权益中心"
            //将users表内的状态更新为vip=1
            this.$http.post('/users/beVIP',
              {
                userId: this.user.userId
              })
            // 更新sessionStorage内的内容
            this.user.vip = 1
            sessionStorage.setItem('user', JSON.stringify(this.user));
            console.log(this.user+"-------------------");
          })
          .catch(() => {
            // on cancel否
            console.log("取消成为VIP")
          });
      }

    },


    // 搜索框,根据食品名称找出包含食品的商家列表
    toSearch() {
      var foodName = document.querySelector('.search-box').value
      // console.log(foodName)
      this.$http.get('/food/getBusinessIdByFoodName', {
        params: {
          foodName: foodName
        }
      }
      )
        .then(res => {
          this.BusinessList = res.data.object;
          console.log(this.BusinessList)
          if (this.BusinessList.length > 0) {
            // console.log("+++++++++++++++")
            // 找到商品了
            this.$router.push({ path: "/businessList", query: { BusinessList: JSON.stringify(this.BusinessList) } })
          }
          else {
            showDialog({
              message: '未找到该商品，已为您随机推荐商家',
            })
            this.$router.push({ path: "/businessList", query: { typeId: Math.floor(Math.random() * 10) + 1 } });

          }
        })
    },

    //点击某个类别，去商家列表组件
    toBusinessList(type) {
      //路由传参
      this.$router.push({ path: "/businessList", query: { typeId: type } });
    },
    //API-获取商家类别列表
    getBusinessType() {
      this.$http.get("/businesstype/listBusinessType").then(res => {
        //console.log(res);
        this.listBusinessType = res.data.object;
      });
    },
    //API-获取综合评分商家列表
    getBusiness() {
      this.$http.get("/business/listBusinessByRemarks").then(res => {
        //console.log(res);
        this.listBusiness = res.data.object;
        this.listBusiness2 = this.listBusiness;
        //console.log(this.listBusiness2);
      });
    },
    //API-获取距离最近商家列表
    nearestDistance() {
      this.choose = 1;
      //console.log(this.choose);
      this.$http.get("/business/listBusinessByDistance").then(res => {
        //console.log(res);
        this.listBusiness = res.data.object;
        this.listBusiness2 = this.listBusiness;
        //console.log(this.listBusiness2);
      });
    },
    //API-获取销量最高商家列表
    highestSales() {
      this.choose = 2;
      //console.log(this.choose);
      this.$http.get("/business/listBusinessBySales").then(res => {
        //console.log(res);
        this.listBusiness = res.data.object;
        this.listBusiness2 = this.listBusiness;
        //console.log(this.listBusiness2);
      });
    },
    //API-获取综合排序商家列表
    comprehensive() {
      this.choose = 0;
      //console.log(this.choose);
      this.getBusiness();
    },
    //API-显示活动按钮
    showPromotions(businessId) {
      // 切换 activeBusinessId，如果点击同一个商家则隐藏
      this.activeBusinessId =
        this.activeBusinessId === businessId ? null : businessId;
    },
    //API-计算评分星级
    countStar(remark) {
      if (remark >= 4.5) return 5;

      if (remark >= 3.5) return 4;

      if (remark >= 2.5) return 3;

      if (remark >= 1.5) return 2;

      if (remark >= 0.5) return 1;
    },
    //API-跳转指定商家
    toBusiness(businessId) {
      //路由传参
      this.$router.push({
        path: "/businessInfo",
        query: { businessId: businessId }
      });
    },
    //API-获取商家被添加至购物车的商品数量
    getBusinessQuantity(businessId) {
      if (this.user == null) return 0;
      // 检查是否已有缓存值
      if (this.businessQuantities[businessId] !== undefined) {
        return this.businessQuantities[businessId];
      }

      // 异步请求数据
      this.$http
        .get("/cart/businessQuantity", {
          params: {
            businessId: businessId,
            userId: this.user.userId
          }
        })
        .then(res => {
          const count = res.data.object.businessCount || 0;
          // 在 Vue 3 中直接修改响应式对象，无需 $set
          this.businessQuantities[businessId] = count;
        })
        .catch(() => {
          this.businessQuantities[businessId] = 0; // 请求失败时默认值
        });

      return 0; // 初始值为 0，等待数据加载
    },
    //API-点击筛选后显示商家类型列表
    showBusinessType() {
      // 切换显示分类的布尔值
      this.showCategories = !this.showCategories;
    },
    //API-按商家类别分类
    categorizeBusiness(typeId) {
      this.$http
        .post("/business/categorizeBusiness", {
          businessList: this.listBusiness2,
          typeId: typeId
        })
        .then(res => {
          console.log(res);
          this.listBusiness = res.data.object;
        })
        .catch(err => {
          console.error(err);
        });
    },
    getBusinessListCount() {
      this.$http.get("/business/getBusinessListCount").then(res => {
        //console.log(res);
        this.count = res.data.object;
      });
    },
    mapActivityTypeToClass(activityType) {
      const typeMap = {
        "新": "new",
        "特": "discount",
        "会": "super"
      };
      return typeMap[activityType] || "default";
    }
  },
  mounted() {

    // 重新获取用户信息
   this.getUserInfo()

    document.onscroll = () => {
      //获取滚动条位置
      let s1 = document.documentElement.scrollTop;
      let s2 = document.body.scrollTop;
      let scroll = s1 == 0 ? s2 : s1;
      //获取视口宽度
      let width = document.documentElement.clientWidth;

      //获取顶部固定块
      //   let search =  document.getElementById('fixedBox');
      let search = this.$refs.fixedBox;
      //判断滚动条超过视口宽度的12%时，搜索块变固定定位
      if (scroll > width * 0.12) {
        search.style.position = "fixed";
        search.style.left = "0";
        search.style.top = "0";
      } else {
        search.style.position = "static";
      }
    };
    this.getBusinessType();
    this.getBusiness();
    this.getBusinessListCount();
    //console.log(this.user);
  },
  unmounted() {
    //当切换到其他组件时，就不需要document滚动条事件，所以将此事件去掉
    document.onscroll = null;
  }
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;

  display: flex;
  align-items: center;
}

.wrapper header .icon-location-box {
  width: 3.5vw;
  height: 3.5vw;
  margin: 0 1vw 0 3vw;
}

.wrapper header .location-text {
  font-size: 4.5vw;
  font-weight: 700;
  color: #fff;
}

.wrapper header .location-text {
  margin-left: 1vw;
}

/****************** search ******************/
.wrapper .search {
  width: 100%;
  height: 13vw;
}

.wrapper .search .search-fixed-top {
  width: 100%;
  height: 13vw;
  background-color: #0097ff;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  /* 设置较高的层级值 */
}

.wrapper .search .search-fixed-top .search-box {
  width: 90%;
  height: 9vw;
  background-color: #fff;
  border-radius: 2px;

  display: flex;
  justify-content: center;
  align-items: center;

  font-size: 4.3vw;
  color: #aeaeae;
  font-family: "宋体";
  /*此样式是让文本选中状态无效*/
  user-select: none;
}

.wrapper .search .search-fixed-top .search-box .fa-search {
  margin-right: 1vw;
}

/****************** 点餐分类部分 ******************/
.wrapper .foodtype {
  width: 100%;
  height: 48vw;

  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  /*要使用align-content。10个子元素将自动换行为两行，而且两行作为一个整体垂直居中*/
  align-content: center;
}

.wrapper .foodtype li {
  /*一共10个子元素，通过计算，子元素宽度在16.7 ~ 20 之间，才能保证换两行*/
  width: 18vw;
  height: 20vw;

  display: flex;
  /*弹性盒子主轴方向设为column，然后仍然是垂直水平方向居中*/
  flex-direction: column;
  justify-content: center;
  align-items: center;

  user-select: none;
  cursor: pointer;
}

.wrapper .foodtype li img {
  width: 12vw;
  /*视频讲解时高度设置为12vw，实际上设置为10.3vw更佳*/
  height: 10.3vw;
}

.wrapper .foodtype li p {
  font-size: 3.2vw;
  color: #666;
}

/****************** 横幅广告部分 ******************/
.wrapper .banner {
  /**
		 * 设置容器宽度95%，然后水平居中，这样两边留白; 
		 * 这里不能用padding，因为背景图片也会覆盖padding
		 */
  width: 95%;
  margin: 0 auto;
  height: 29vw;

  /*此三个样式组合，可以保证背景图片充满整个容器*/
  background-image: url(../assets/index_banner.png);
  background-repeat: no-repeat;
  background-size: cover;

  box-sizing: border-box;
  padding: 2vw 6vw;
}

.wrapper .banner h3 {
  font-size: 4.2vw;
  margin-bottom: 1.2vw;
}

.wrapper .banner p {
  font-size: 3.4vw;
  color: #666;
  margin-bottom: 2.4vw;
}

.wrapper .banner a {
  font-size: 3vw;
  color: #c79060;
  font-weight: 700;
}

/****************** 超级会员部分 ******************/
.wrapper .supermember {
  /*这里也设置容器宽度95%，不能用padding，因为背景色也会充满padding*/
  width: 95%;
  margin: 0 auto;
  height: 11.5vw;
  background-color: #feedc1;
  margin-top: 1.3vw;
  border-radius: 2px;
  color: #644f1b;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .supermember .left {
  display: flex;
  align-items: center;
  margin-left: 4vw;
  user-select: none;
}

.wrapper .supermember .left img {
  width: 6vw;
  height: 6vw;
  margin-right: 2vw;
}

.wrapper .supermember .left h3 {
  font-size: 4vw;
  margin-right: 2vw;
}

.wrapper .supermember .left p {
  font-size: 3vw;
}

.wrapper .supermember .right {
  font-size: 3vw;
  margin-right: 4vw;
  cursor: pointer;
}

/****************** 推荐商家部分 ******************/
.wrapper .recommend {
  width: 100%;
  height: 14vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .recommend .recommend-line {
  width: 6vw;
  height: 0.2vw;
  background-color: #888;
}

.wrapper .recommend p {
  font-size: 4vw;
  margin: 0 4vw;
}

/****************** 推荐方式部分 ******************/
.wrapper .recommendtype {
  width: 100%;
  height: 5vw;
  margin-bottom: 5vw;

  display: flex;
  justify-content: space-around;
  align-items: center;
}

.wrapper .recommendtype li {
  font-size: 3.5vw;
  color: #555;
}

.category-box {
  position: absolute;
  top: 300px;
  /* 调整顶部位置，使它向下移动 */
  right: 80px;
  /* 调整右侧位置，使它向左移动 */
  background-color: white;
  border: 1px solid #ccc;
  padding: 10px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  width: 80px;
  /* 增大宽度来适应内容 */
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
  text-align: center;
  /* 使整个box中的内容居中 */
}

.category-box ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.category-box ul li {
  padding: 5px 0;
}

.category-box ul li p {
  font-size: 16px;
  /* 增大字体 */
  margin: 0;
  /* 去掉多余的外边距 */
}

.rotateFilter {
  transform: rotate(270deg);
  transition: transform 0.2s ease;
  /* 动画过渡效果 */
}

/****************** 推荐商家列表部分 ******************/
.wrapper .business {
  width: 100%;
  padding-bottom: 14vw;
}

.wrapper .business li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  border-bottom: solid 1px #ddd;
  display: flex;
}

.wrapper .business li .business-img {
  position: relative;
  /* 将图片容器设置为相对定位，使其成为定位的参考 */
  display: inline-block;
  /* 保持图片的正常布局 */
}

.wrapper .business li img {
  width: 18vw;
  height: 18vw;
}

.wrapper .business li .business-img-quantity {
  width: 5vw;
  /* 设置宽度 */
  height: 5vw;
  /* 设置高度 */
  background-color: red;
  /* 红底 */
  color: #fff;
  /* 白字 */
  font-size: 3vw;
  /* 调整字体大小 */
  border-radius: 50%;
  /* 圆形背景 */

  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */

  position: absolute;
  /* 绝对定位 */
  top: -1vw;
  /* 调整到图片的顶部偏移 */
  right: -1vw;
  /* 调整到图片的右侧偏移 */

  z-index: 1;
  /* 确保在图片上方显示 */
}

.wrapper .business li .business-info {
  width: 100%;
  box-sizing: border-box;
  padding-left: 3vw;
}

.wrapper .business li .business-info .business-info-h {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
}

.wrapper .business li .business-info .business-info-h h3 {
  font-size: 4vw;
  color: #333;
}

.wrapper .business li .business-info .business-info-h .business-info-like {
  width: 1.6vw;
  height: 3.4vw;
  background-color: #666;
  color: #fff;
  font-size: 4vw;
  margin-right: 4vw;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .business li .business-info .business-info-star {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3.1vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left {
  display: flex;
  align-items: center;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left .fa-star {
  color: #fec80e;
  margin-right: 0.5vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-left p {
  color: #666;
  margin-left: 1vw;
}

.wrapper .business li .business-info .business-info-star .business-info-star-right {
  background-color: #0097ff;
  color: #fff;
  font-size: 2.4vw;
  border-radius: 2px;
  padding: 0 0.6vw;
}

.wrapper .business li .business-info .business-info-delivery {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;

  color: #666;
  font-size: 3.1vw;
}

.wrapper .business li .business-info .business-info-explain {
  display: flex;
  align-items: center;
  margin-bottom: 3vw;
}

.wrapper .business li .business-info .business-info-explain div {
  border: solid 1px #ddd;
  font-size: 2.8vw;
  color: #666;
  border-radius: 3px;
  padding: 0 0.1vw;
}

/* 从这里开始 */
.wrapper .business li .business-info .business-info-promotion-of-left {
  display: flex;
  flex-direction: column;
  /* 垂直排列子元素 */
  justify-content: flex-start;
  /* 从上到下的排列 */
  align-items: flex-start;
  /* 左对齐 */
  margin-bottom: 1.8vw;
}

.wrapper .business li .business-info .business-info-promotion-of-left:first-of-type {
  justify-content: flex-end;
  /* 第一个 .business-info-promotion-of-left 右对齐 */
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-left {
  display: flex;
  align-items: center;
  margin-bottom: 0.5vw;
  /* 子元素间距调整 */
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-left .business-info-promotion-left-incon {
  width: 4vw;
  height: 4vw;
  border-radius: 3px;
  font-size: 3vw;
  color: #fff;

  display: flex;
  justify-content: center;
  align-items: center;
}

/* 针对不同类型的样式 */
.wrapper .business-info-promotion-left-incon.activity-type-new {
  background-color: #70bc46;
}

.wrapper .business-info-promotion-left-incon.activity-type-discount {
  background-color: #9933ff;
}

.wrapper .business-info-promotion-left-incon.activity-type-super {
  background-color: #f1884f;
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-left p {
  color: #666;
  font-size: 3vw;
  margin-left: 2vw;
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-right {
  display: flex;
  align-items: center;
  font-size: 2.5vw;
  color: #999;
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-right p {
  margin-right: 2vw;
  cursor: pointer;
  /* 添加点击样式 */
}

.wrapper .business li .business-info .business-info-promotion-of-left .business-info-promotion-right i {
  margin-left: 0.5vw;
  font-size: 2.5vw;
}

.rotated {
  transform: rotate(90deg);
  /* 旋转 90 度 */
}
</style>